import ProFormUpload from '@/components/ProFormUpload';
import shopClassifyApi from '@/pages/Shop/ClassifyManagement/request';
import shopGroupApi from '@/pages/Shop/GroupBaseManagement/request';
import api from '@/pages/Shop/ListManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ProFormGroup,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: ShopListManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}

const defaultFormData: ShopListManagementApi.FormData = {
  shopName: '',
  isEnabled: false,
  createTime: '',
  shopClassifyId: '',
  shopClassifyName: '',
  shopAddress: '',
  longitude: 0,
  latitude: 0,
  synopsis: '',
  contactPhone: '',
  groupId: '',
  groupName: '',
  director: '',
  pic: [],
  shopType: '',
  businessHours: '',
};
function ShopListManagementForm(props: Props) {
  const { data, isEdit = false } = props;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState<ShopListManagementApi.FormData>({ ...defaultFormData });
  const [info, setInfo] = useState<Partial<ShopListManagementApi.InfoResponse>>({});
  const [shopClassifyList, setShopClasifyList] = useState<ShopClassifyManagementApi.InfoResponse[]>(
    [],
  );
  const [shopGroupList, setShopGroupList] = useState<ShopbaseManagementApi.ListResponse[]>([]);

  const shopClassifyListOptions = useMemo(
    () => shopClassifyList.map((item) => ({ label: item.classifyName, value: item.id })),
    [shopClassifyList],
  );
  const shopGroupListOptions = useMemo(
    () => shopGroupList.map((item) => ({ label: item.groupName, value: item.id })),
    [shopGroupList],
  );

  const getAllShopClassifyList = async () => {
    const data = await shopClassifyApi.getAllList();
    setShopClasifyList(data);
  };
  const getAllShopGroupList = async () => {
    const data = await shopGroupApi.getAllList();
    setShopGroupList(data);
  };
  const getInfo = async (params: ShopListManagementApi.InfoParams) => {
    const info = await api.getInfo(params);
    const { pic, ...data } = info;
    const formData: ShopListManagementApi.FormData = { ...data, pic: [] };
    if (pic) {
      formData.pic = [
        {
          uid: pic,
          name: pic,
          url: pic,
        },
      ];
    }
    setInfo(info);
    form.setFieldsValue(formData);
    setFormData(formData);
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      getAllShopClassifyList();
      getAllShopGroupList();
      if (data && data.id) {
        getInfo({ id: data.id });
      }
    } else {
      setInfo({});
      form.resetFields();
      setFormData({ ...defaultFormData });
      props.onCancel?.();
    }
  };
  const onSubmit = async () => {
    const {
      shopName,
      shopClassifyId,
      shopAddress,
      synopsis,
      longitude,
      latitude,
      isEnabled,
      createTime,
      contactPhone,
      groupId,
      director,
      pic,
      shopType,
      businessHours,
    } = formData;
    const { id = '' } = info;

    if (isEdit) {
      const params: ShopListManagementApi.UpdateParams = {
        id,
        shopName,
        shopClassifyId,
        shopAddress,
        synopsis,
        longitude,
        latitude,
        isEnabled,
        createTime,
        contactPhone,
        groupId,
        director,
        pic: pic[0].url,
        shopType,
        businessHours,
      };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: ShopListManagementApi.CreateParams = {
        shopName,
        shopClassifyId,
        shopAddress,
        synopsis,
        longitude,
        latitude,
        isEnabled,
        createTime,
        contactPhone,
        groupId,
        director,
        pic: pic[0].url,
        shopType,
        businessHours,
      };
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}门店`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 750,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <PlusOutlined />
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <ProFormGroup>
        <ProFormText
          width="md"
          required
          name="shopName"
          label="门店名称"
          placeholder="请输入门店名称"
          rules={[{ required: true }]}
          fieldProps={{
            value: formData.shopName,
            onChange: (e) => setFormData({ ...formData, shopName: e.target.value }),
          }}
        />
        <ProFormUpload
          name="pic"
          label="门店图片"
          placeholder="请上传图片"
          max={1}
          rules={[{ required: true }]}
          file={formData.pic}
          onChangeFile={(file) => {
            setFormData({ ...formData, pic: file });
          }}
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormSelect
          width="md"
          required
          name="groupId"
          label="集团门店"
          placeholder="请选择集团门店"
          rules={[{ required: true }]}
          options={shopGroupListOptions}
          fieldProps={{
            value: formData.groupId,
            onChange: (value) => {
              setFormData({ ...formData, groupId: value });
            },
          }}
        />
        <ProFormSelect
          width="md"
          required
          name="shopClassifyId"
          label="门店分类"
          placeholder="请选择门店分类"
          rules={[{ required: true }]}
          options={shopClassifyListOptions}
          fieldProps={{
            value: formData.shopClassifyId,
            onChange: (value) => {
              setFormData({ ...formData, shopClassifyId: value });
            },
          }}
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormText
          width="md"
          required
          name="director"
          label="负责人"
          placeholder="请输入负责人"
          rules={[{ required: true }]}
          fieldProps={{
            value: formData.director,
            onChange: (e) => setFormData({ ...formData, director: e.target.value }),
          }}
        />
        <ProFormText
          width="md"
          required
          name="contactPhone"
          label="联系电话"
          placeholder="请输入联系电话"
          rules={[{ required: true }, { pattern: /^1\d{10}/, message: '请输入正确的联系电话' }]}
          fieldProps={{
            value: formData.contactPhone,
            onChange: (e) => setFormData({ ...formData, contactPhone: e.target.value }),
          }}
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormText
          width="md"
          required
          name="shopType"
          label="门店类型"
          placeholder="请输入门店类型"
          rules={[{ required: true }]}
          fieldProps={{
            value: formData.shopType,
            onChange: (e) => setFormData({ ...formData, shopType: e.target.value }),
          }}
        />
        <ProFormText
          width="md"
          required
          name="businessHours"
          label="营业时间"
          placeholder="请输入营业时间"
          rules={[{ required: true }]}
          fieldProps={{
            value: formData.businessHours,
            onChange: (e) => setFormData({ ...formData, businessHours: e.target.value }),
          }}
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormTextArea
          width="md"
          required
          name="shopAddress"
          label="门店地址"
          placeholder="请输入门店地址"
          rules={[{ required: true }]}
          fieldProps={{
            value: formData.shopAddress,
            onChange: (e) => setFormData({ ...formData, shopAddress: e.target.value }),
          }}
        />
        <ProFormTextArea
          width="md"
          required
          name="synopsis"
          label="门店描述"
          placeholder="请输入门店描述"
          rules={[{ required: true }]}
          fieldProps={{
            value: formData.synopsis,
            onChange: (e) => setFormData({ ...formData, synopsis: e.target.value }),
          }}
        />
      </ProFormGroup>

      {/* <ProFormDatePicker
        required
        width="lg"
        name="createTime"
        label="创建时间"
        placeholder="请选择创建时间"
        rules={[{ required: true }]}
        fieldProps={{
          value: dayjs(formData.createTime),
          onChange: (_, date) => {
            setFormData({ ...formData, createTime: date });
          },
        }}
      /> */}

      <ProFormSwitch
        required
        name="isEnabled"
        label="状态"
        placeholder="请选择状态"
        checkedChildren="启用"
        unCheckedChildren="禁用"
        rules={[{ required: true }]}
        fieldProps={{
          checked: formData.isEnabled,
          onChange: (value) => {
            setFormData({ ...formData, isEnabled: value });
          },
        }}
      />
    </DrawerForm>
  );
}

export default ShopListManagementForm;
